package com.haohan.jingyuan.customer.service;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.haohan.jingyuan.common.enums.ErrorEnum;
import com.haohan.jingyuan.common.exception.BusinessException;
import com.haohan.jingyuan.common.util.EntityUtil;
import com.haohan.jingyuan.customer.dao.CustomerGroupMapper;
import com.haohan.jingyuan.customer.dao.CustomerInfoMapper;
import com.haohan.jingyuan.customer.dao.CustomerTagMapper;
import com.haohan.jingyuan.customer.dto.req.CreateCustomerRequest;
import com.haohan.jingyuan.customer.dto.req.DeleteCustomerRequest;
import com.haohan.jingyuan.customer.dto.req.QueryCustomerListRequest;
import com.haohan.jingyuan.customer.dto.req.UpdateCustomerRequest;
import com.haohan.jingyuan.customer.dto.resp.CustomerInfoResp;
import com.haohan.jingyuan.customer.dto.resp.CustomerListResp;
import com.haohan.jingyuan.customer.entity.CustomerGroupInfo;
import com.haohan.jingyuan.customer.entity.CustomerInfo;
import com.haohan.jingyuan.customer.entity.CustomerTag;
import com.haohan.jingyuan.customer.helper.CustomerInfoRespHelper;
import com.haohan.jingyuan.gateway.holder.UserContextHolder;
import com.haohan.jingyuan.sys.service.DictService;
import com.haohan.jingyuan.util.UuidUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 客户服务实现类
 *
 * @ClassName CustomerService
 * @Description 客户相关业务逻辑实现
 * @Author hexijun
 * @Time 2025/01/19 10:00
 * @Version 1.0
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class CustomerService {

    /**
     * 客户信息Mapper
     */
    private final CustomerInfoMapper customerInfoMapper;

    /**
     * 客户分组Mapper
     */
    private final CustomerGroupMapper customerGroupMapper;

    /**
     * 客户标签Mapper
     */
    private final CustomerTagMapper customerTagMapper;

    /**
     * 字典服务
     */
    private final DictService dictService;

    /**
     * 创建客户
     *
     * @param request 创建客户请求
     * @return 客户信息
     */
    public CustomerInfoResp createCustomer(CreateCustomerRequest request) {
        log.info("CustomerService.createCustomer BEGIN ==> name: {}", request.getName());

        // 校验分组是否存在且type=1（客户分组）（如果传入了分组）
        if (request.getCategory() != null && !request.getCategory().trim().isEmpty()) {
            CustomerGroupInfo group = customerGroupMapper.findByGroupIdAndType(request.getCategory(), 1);
            if (group == null) {
                throw new BusinessException(ErrorEnum.GROUP_NOT_FOUND);
            }
        }

        // 检查客户名称是否已存在
        CustomerInfo existingCustomer = customerInfoMapper.findByName(request.getName());
        if (existingCustomer != null) {
            throw new BusinessException(ErrorEnum.CUSTOMER_ALREADY_EXISTS);
        }

        // 校验与规范化标签
        String tags = getTagsString(request.getTags());

        // 创建客户信息
        CustomerInfo customerInfo = new CustomerInfo();
        customerInfo.setCustomerId(UuidUtil.generateId("CUST_", 8));
        customerInfo.setName(request.getName());
        customerInfo.setIndustry(request.getIndustry());
        customerInfo.setOwner(request.getOwner());
        customerInfo.setCategory(request.getCategory());
        customerInfo.setTags(tags);
        customerInfo.setContactName(request.getContactName());
        customerInfo.setContactPhone(request.getContactPhone());
        customerInfo.setRemarks(request.getRemarks());
        EntityUtil.setCreateAndModifyInfo(customerInfo, UserContextHolder.getCurrentUserName());

        // 保存到数据库
        int result = customerInfoMapper.insert(customerInfo);
        if (result <= 0) {
            throw new BusinessException(ErrorEnum.DATABASE_ERROR);
        }

        CustomerInfoResp customerInfoResp = CustomerInfoRespHelper.convert2CustomerInfoResp(customerInfo);
        log.info("CustomerService.createCustomer END ==> {}", customerInfoResp);
        return customerInfoResp;
    }

    /**
     * 更新客户
     *
     * @param request 更新客户请求
     * @return 客户信息
     */
    public CustomerInfoResp updateCustomer(UpdateCustomerRequest request) {
        log.info("CustomerService.updateCustomer BEGIN ==> id: {}", request.getId());

        // 查询客户是否存在
        Long id = Long.parseLong(request.getId());
        CustomerInfo customerInfo = customerInfoMapper.selectById(id);
        if (customerInfo == null) {
            throw new BusinessException(ErrorEnum.CUSTOMER_NOT_FOUND);
        }

        // 校验分组是否存在且type=1（客户分组）（如果传入了分组）
        if (request.getCategory() != null && !request.getCategory().trim().isEmpty()) {
            CustomerGroupInfo group = customerGroupMapper.findByGroupIdAndType(request.getCategory(), 1);
            if (group == null) {
                throw new BusinessException(ErrorEnum.GROUP_NOT_FOUND);
            }
        }

        // 检查客户名称是否与其他客户重复
        CustomerInfo existingCustomer = customerInfoMapper.findByName(request.getName());
        if (existingCustomer != null && !existingCustomer.getId().equals(id)) {
            throw new BusinessException(ErrorEnum.CUSTOMER_ALREADY_EXISTS);
        }

        // 处理标签字段
        // 如果tags为null，不更新tags字段（保持原值）
        // 如果tags为空数组，将tags设置为null
        // 如果tags有值，校验并规范化后设置
        if (request.getTags() != null) {
            if (request.getTags().isEmpty()) {
                // 空数组表示需要清空tags字段
                customerInfo.setTags("");
            } else {
                // 有值则校验并规范化
                String tags = getTagsString(request.getTags());
                customerInfo.setTags(tags);
            }
        }

        // 更新客户信息
        customerInfo.setName(request.getName());
        customerInfo.setIndustry(request.getIndustry());
        customerInfo.setOwner(request.getOwner());
        customerInfo.setCategory(request.getCategory());
        customerInfo.setContactName(request.getContactName());
        customerInfo.setContactPhone(request.getContactPhone());
        customerInfo.setRemarks(request.getRemarks());
        // 设置修改信息
        EntityUtil.setModifyInfo(customerInfo, UserContextHolder.getCurrentUserName());

        // 更新数据库
        int result = customerInfoMapper.updateById(customerInfo);
        if (result <= 0) {
            throw new BusinessException(ErrorEnum.DATABASE_ERROR);
        }

        CustomerInfoResp customerInfoResp = CustomerInfoRespHelper.convert2CustomerInfoResp(customerInfo);
        log.info("CustomerService.updateCustomer END ==> {}", customerInfoResp);
        return customerInfoResp;
    }

    /**
     * 规范化并校验标签：
     * 1) trim去空白；2) 过滤空值；3) 去重；4) 校验每个code存在且type=1（客户标签）
     *
     * @param tags 标签编码列表
     * @return 规范化后的标签编码字符串
     */
    private String getTagsString(List<String> tags) {
        if (CollectionUtil.isEmpty(tags)) {
            return null;
        }
        // trim去空白并过滤空值
        List<String> normalizedTags = new ArrayList<>();
        for (String tag : tags) {
            if (tag != null) {
                String trimmed = tag.trim();
                if (!trimmed.isEmpty()) {
                    normalizedTags.add(trimmed);
                }
            }
        }
        if (normalizedTags.isEmpty()) {
            return null;
        }
        // 去重校验
        Set<String> tagsSet = new HashSet<>(normalizedTags);
        if (tagsSet.size() != normalizedTags.size()) {
            throw new BusinessException(ErrorEnum.TAG_REPEAT);
        }
        // 校验标签存在且type=1（客户标签）
        List<CustomerTag> result = customerTagMapper.findByCodeListAndType(tagsSet, 1);
        if (result.size() != tagsSet.size()) {
            throw new BusinessException(ErrorEnum.TAG_NOT_FOUND);
        }
        return String.join(",", normalizedTags);
    }

    /**
     * 删除客户
     *
     * @param request 删除客户请求
     * @return 删除结果
     */
    public boolean deleteCustomer(DeleteCustomerRequest request) {
        log.info("CustomerService.deleteCustomer BEGIN ==> id: {}", request.getId());

        // 查询客户是否存在
        Long id = Long.parseLong(request.getId());
        CustomerInfo customerInfo = customerInfoMapper.selectById(id);
        if (customerInfo == null) {
            throw new BusinessException(ErrorEnum.CUSTOMER_NOT_FOUND);
        }

        // 逻辑删除
        customerInfo.setIsDeleted("Y");
        EntityUtil.setModifyInfo(customerInfo, UserContextHolder.getCurrentUserName());

        // 更新数据库
        int result = customerInfoMapper.updateById(customerInfo);
        if (result <= 0) {
            throw new BusinessException(ErrorEnum.DATABASE_ERROR);
        }

        log.info("CustomerService.deleteCustomer END ==> id: {}", request.getId());
        return true;
    }

    /**
     * 查询客户列表
     *
     * @param request 查询客户列表请求
     * @return 客户列表
     */
    public CustomerListResp queryCustomerList(QueryCustomerListRequest request) {
        log.info("CustomerService.queryCustomerList BEGIN ==> {}", request);

        // 创建分页对象
        Page<CustomerInfo> page = new Page<>(request.getPageNum(), request.getPageSize());

        // 分页查询
        IPage<CustomerInfo> customerPage = customerInfoMapper.selectCustomerListPage(page,
                request.getName(), request.getIndustry(), request.getOwner(),
                request.getCategory(), request.getTags(),
                request.getGmtCreatedStart(), request.getGmtCreatedEnd());

        // 批量查询行业字典信息（使用缓存，返回Map，key为dictKey，value为dictValue）
        final Map<String, String> industryMap = dictService.getAllIndustryType();

        // 批量查询分组信息
        List<CustomerGroupInfo> groupList = customerGroupMapper.selectByType(1);
        final Map<String, CustomerGroupInfo> groupMap = groupList.stream()
                .collect(Collectors.toMap(CustomerGroupInfo::getGroupId, group -> group));

        // 批量查询标签信息
        Set<String> allTagCodes = new HashSet<>();
        for (CustomerInfo record : customerPage.getRecords()) {
            if (record.getTags() != null && !record.getTags().trim().isEmpty()) {
                String[] tagCodes = record.getTags().split(",");
                for (String tagCode : tagCodes) {
                    String trimmed = tagCode.trim();
                    if (!trimmed.isEmpty()) {
                        allTagCodes.add(trimmed);
                    }
                }
            }
        }
        final Map<String, CustomerTag> tagMap;
        if (!allTagCodes.isEmpty()) {
            List<CustomerTag> tagList = customerTagMapper.findByCodeListAndType(allTagCodes, 1);
            tagMap = tagList.stream()
                    .collect(Collectors.toMap(CustomerTag::getTagCode, tag -> tag));
        } else {
            tagMap = new HashMap<>();
        }

        // 转换为响应对象
        List<CustomerInfoResp> customerList = new ArrayList<>();
        for (CustomerInfo record : customerPage.getRecords()) {
            customerList.add(CustomerInfoRespHelper.convert2CustomerInfoResp(record, industryMap, groupMap, tagMap));
        }

        CustomerListResp response = new CustomerListResp();
        response.setCustomerList(customerList);
        response.setTotal(customerPage.getTotal());
        response.setPageNum(request.getPageNum());
        response.setPageSize(request.getPageSize());
        response.setTotalPages((int) customerPage.getPages());

        log.info("CustomerService.queryCustomerList SUCCESS ==> {}", response);
        return response;
    }
}
